

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/blog/img/fluid.png">
  <link rel="icon" href="/blog/images/base.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Airfe">
  <meta name="keywords" content="">
  
    <meta name="description" content="本文介绍TypeScrip的基本数据类型。">
<meta property="og:type" content="article">
<meta property="og:title" content="TypeScript(一) 简介和基本数据类型">
<meta property="og:url" content="https://airfe.gitee.io/blog/2024/04/09/TypeScript(%E4%B8%80)%20%E7%AE%80%E4%BB%8B%E5%92%8C%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B/index.html">
<meta property="og:site_name" content="Airfe的博客">
<meta property="og:description" content="本文介绍TypeScrip的基本数据类型。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/TypeScript.png">
<meta property="article:published_time" content="2024-04-09T03:00:00.000Z">
<meta property="article:modified_time" content="2024-04-13T03:04:52.666Z">
<meta property="article:author" content="Airfe">
<meta property="article:tag" content="ts">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://markdown-1307246189.cos.ap-chongqing.myqcloud.com/pageImage/TypeScript.png">
  
  
  
    <meta name="referrer" content="no-referrer" />
  
  <title>TypeScript(一) 简介和基本数据类型 - Airfe的博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/blog/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/blog/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/blog/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"airfe.gitee.io","root":"/blog/","version":"1.9.4","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":"699a5d71ac7179b23874a59b0666a6f6","google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","app_key":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com","path":"window.location.pathname","ignore_local":false}},"search_path":"/blog/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/blog/js/utils.js" ></script>
  <script  src="/blog/js/color-schema.js" ></script>
  

  
    <!-- Baidu Analytics -->
    <script async>
      if (!Fluid.ctx.dnt) {
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?699a5d71ac7179b23874a59b0666a6f6";
          var s = document.getElementsByTagName("script")[0];
          s.parentNode.insertBefore(hm, s);
        })();
      }
    </script>
  

  

  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/blog/">
      <strong>Airfe</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/blog/links/">
                <i class="iconfont icon-link-fill"></i>
                <span>友链</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/blog/images/bg.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="TypeScript(一) 简介和基本数据类型"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2024-04-09 11:00" pubdate>
          2024年04月09日
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          6.5k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          55 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">TypeScript(一) 简介和基本数据类型</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="TypeScript简介"><a href="#TypeScript简介" class="headerlink" title="TypeScript简介"></a>TypeScript简介</h1><p>Typed JavaScript at Any Scale.</p>
<p>是以JavaScript为基础构建的语言，一个JavaScript的超集，扩展了JavaScript，并添加了类型。</p>
<p>TypeScript提供了一套静态类型检测机制, 可以帮助我们在编译时就发现错误。TS不能被JS解析器直接执行，需要<strong>编译</strong>为JS，浏览器才能执行。</p>
<blockquote>
<p>js中的类型只是针对值而言，在ts中类型可以设定在变量身上。</p>
</blockquote>
<p>TypeScript特点</p>
<ul>
<li>支持最新的JavaScript新特特性</li>
<li>支持代码静态检查</li>
<li>支持诸如C,C++,Java,Go等后端语言中的特性 (枚举、泛型、类型转换、命名空间、声明文件、类、接口等)</li>
</ul>
<h1 id="开发环境搭建"><a href="#开发环境搭建" class="headerlink" title="开发环境搭建"></a>开发环境搭建</h1><ol>
<li><p>下载并安装<strong>Node.js</strong></p>
</li>
<li><p>使用npm全局安装typescript编译器  <code>npm i -g typescript</code></p>
</li>
<li><p>创建一个ts文件</p>
</li>
<li><p>使用tsc对文件进行编译  <code>tsc xxx.ts</code></p>
</li>
<li><p>如果出现报错信息 tsc : 无法加载文件 D:\Nodejs\node_global\tsc.ps1，因为在此系统上禁止运行脚本……</p>
<p>原因：执行策略的问题（权限问题）</p>
<p>解决方法：<code>Set-ExecutionPolicy -Scope CurrentUser</code>     <code>RemoteSigned</code></p>
<p>只要查看<code>Get-ExecutionPolicy</code>  得到的结果是<code>RemoteSigned</code> 而不是 <code>Restricted</code>就已经成功解决</p>
</li>
</ol>
<h1 id="基本类型"><a href="#基本类型" class="headerlink" title="基本类型"></a>基本类型</h1><h2 id="类型声明"><a href="#类型声明" class="headerlink" title="类型声明"></a>类型声明</h2><ul>
<li><p>类型声明给变量（参数、形参）设置了类型，使得变量只能存储某种类型的值；</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> 变量: 类型;<br><br><span class="hljs-keyword">let</span> 变量: 类型 = 值;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">fn</span>(<span class="hljs-params">参数: 类型, 参数: 类型</span>): 类型&#123;<br>    ...<br>&#125;<br></code></pre></td></tr></table></figure>
</li>
<li><p>自动类型判断</p>
<ul>
<li>TS拥有自动的类型判断机制</li>
<li>当<strong>同时声明变量且赋值</strong>，TS编译器会自动判断变量的类型</li>
<li>所以如果你的变量的声明和赋值时同时进行的，可以省略掉类型声明</li>
</ul>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 如果变量的声明和赋值是同时进行的，TS可以自动对变量进行类型检查</span><br><span class="hljs-keyword">let</span> b = <span class="hljs-literal">false</span>;<br><span class="hljs-comment">// b会有红色波浪线，因为TS编译器已经自动判断变量的类型为boolean</span><br>b = <span class="hljs-string">&#x27;hello&#x27;</span><br></code></pre></td></tr></table></figure>

<h2 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h2><table>
<thead>
<tr>
<th><strong>类型</strong></th>
<th><strong>例子</strong></th>
<th><strong>描述</strong></th>
</tr>
</thead>
<tbody><tr>
<td>number</td>
<td>1, -33, 2.5</td>
<td>任意数字</td>
</tr>
<tr>
<td>string</td>
<td>‘hi’, “hi”, <code>hi</code></td>
<td>任意字符串</td>
</tr>
<tr>
<td>boolean</td>
<td>true、false</td>
<td>布尔值true或false</td>
</tr>
<tr>
<td>字面量</td>
<td>其本身</td>
<td>限制变量的值就是该字面量的值</td>
</tr>
<tr>
<td>any</td>
<td>*</td>
<td>任意类型</td>
</tr>
<tr>
<td>unknown</td>
<td>*</td>
<td>类型安全的any</td>
</tr>
<tr>
<td>void</td>
<td>空值（undefined）</td>
<td>没有值（或undefined）</td>
</tr>
<tr>
<td>never</td>
<td>没有值</td>
<td>不能是任何值</td>
</tr>
<tr>
<td>object</td>
<td>{name:’孙悟空’}</td>
<td>任意的JS对象</td>
</tr>
<tr>
<td>array</td>
<td>[1,2,3]</td>
<td>任意JS数组</td>
</tr>
<tr>
<td>tuple</td>
<td>[4,5]</td>
<td>元素，TS新增类型，固定长度数组</td>
</tr>
<tr>
<td>enum</td>
<td>enum{A, B}</td>
<td>枚举，TS中新增类型</td>
</tr>
</tbody></table>
<p>TypeScript支持与JavaScript几乎相同的数据类型，此外还提供了元组（Tuple）、Any、Unknown、Void、Never、枚举（enum）等实用的类型方便我们使用。</p>
<h3 id="原始类型"><a href="#原始类型" class="headerlink" title="原始类型"></a>原始类型</h3><p><strong>boolean</strong>、<strong>number</strong>、<strong>string</strong> 、<strong>null</strong>、<strong>undefined</strong>、**symbol **和 ES10 中的新类型 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/BigInt"><code>bigint </code></a>，这7种是原始类型。</p>
<h4 id="boolean-布尔值"><a href="#boolean-布尔值" class="headerlink" title="boolean(布尔值)"></a>boolean(布尔值)</h4><p>在<strong>TypeScript</strong>中，<code>boolean</code> 是 JavaScript 中的基本类型，而 <code>Boolean</code> 是 JavaScript 中的构造函数。其他基本类型（除了 <code>null</code> 和 <code>undefined</code>）一样。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-comment">// 编译通过</span><br><span class="hljs-keyword">let</span> <span class="hljs-attr">isDone</span>: <span class="hljs-built_in">boolean</span> = <span class="hljs-literal">false</span>;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">createdByBoolean</span>: <span class="hljs-built_in">boolean</span> = <span class="hljs-title class_">Boolean</span>(<span class="hljs-number">1</span>);<br><span class="hljs-comment">// 使用构造函数 Boolean 创造的对象不是布尔值，编译报错</span><br><span class="hljs-keyword">let</span> <span class="hljs-attr">createdByNewBoolean</span>: <span class="hljs-built_in">boolean</span> = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Boolean</span>(<span class="hljs-number">1</span>);<br></code></pre></td></tr></table></figure>

<blockquote>
<p><code>new Boolean()</code> 返回的是一个 <code>Boolean</code> 对象<code>let createdByNewBoolean: Boolean = new Boolean(1);</code></p>
</blockquote>
<h4 id="number和bigint"><a href="#number和bigint" class="headerlink" title="number和bigint"></a>number和bigint</h4><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">big</span>: <span class="hljs-built_in">bigint</span> =  <span class="hljs-number">100n</span>;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">num</span>: <span class="hljs-built_in">number</span> = <span class="hljs-number">6</span>;<br>big = num;<br>num = big;<br><span class="hljs-comment">// 会抛出一个类型不兼容的 ts(2322) 错误。</span><br></code></pre></td></tr></table></figure>

<h4 id="string-字符串"><a href="#string-字符串" class="headerlink" title="string(字符串)"></a>string(字符串)</h4><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">let</span> <span class="hljs-attr">myName</span>: string = <span class="hljs-string">&#x27;Tom&#x27;</span>;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">myAge</span>: number = <span class="hljs-number">25</span>;<br><br><span class="hljs-comment">// 模板字符串</span><br><span class="hljs-keyword">let</span> <span class="hljs-attr">sentence</span>: string = <span class="hljs-string">`Hello, my name is <span class="hljs-subst">$&#123;myName&#125;</span>.I&#x27;ll be <span class="hljs-subst">$&#123;myAge + <span class="hljs-number">1</span>&#125;</span> years old next month.`</span>;<br></code></pre></td></tr></table></figure>

<p>编译结果：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">var</span> myName = <span class="hljs-string">&#x27;Tom&#x27;</span>;<br><span class="hljs-keyword">var</span> myAge = <span class="hljs-number">25</span>;<br><span class="hljs-comment">// 模板字符串</span><br><span class="hljs-keyword">var</span> sentence = <span class="hljs-string">&quot;Hello, my name is &quot;</span> + myName + <span class="hljs-string">&quot;.I&#x27;ll be &quot;</span> + (myAge + <span class="hljs-number">1</span>) + <span class="hljs-string">&quot; years old next month.&quot;</span>;<br></code></pre></td></tr></table></figure>

<p>其中 &#96; 用来定义 ES6 中的模板字符串，${expr} 用来在模板字符串中嵌入表达式。</p>
<h4 id="null和-undefined"><a href="#null和-undefined" class="headerlink" title="null和 undefined"></a>null和 undefined</h4><p>默认情况下 <code>null</code> 和 <code>undefined</code> 是所有类型的子类型。 就是说你可以把 <code>null</code> 和 <code>undefined</code> 赋值给其他类型。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">u</span>: <span class="hljs-literal">undefined</span> = <span class="hljs-literal">undefined</span>;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">n</span>: <span class="hljs-literal">null</span> = <span class="hljs-literal">null</span>;<br><br><span class="hljs-comment">// null和undefined赋值给string</span><br><span class="hljs-keyword">let</span> <span class="hljs-attr">str</span>:<span class="hljs-built_in">string</span> = <span class="hljs-string">&quot;666&quot;</span>;<br>str = <span class="hljs-literal">null</span><br>str= <span class="hljs-literal">undefined</span><br></code></pre></td></tr></table></figure>

<p>如果你在tsconfig.json指定了<code>&quot;strictNullChecks&quot;:true</code> ，<code>null</code> 和 <code>undefined</code> 只能赋值给 <code>void</code> 和它们各自的类型。</p>
<h4 id="Symbol"><a href="#Symbol" class="headerlink" title="Symbol"></a>Symbol</h4><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">sym</span>: <span class="hljs-built_in">symbol</span> = <span class="hljs-title class_">Symbol</span>(<span class="hljs-string">&quot;me&quot;</span>); <br></code></pre></td></tr></table></figure>

<h3 id="其他类型"><a href="#其他类型" class="headerlink" title="其他类型"></a>其他类型</h3><p>其他类型包括有<strong>enum</strong>、<strong>array</strong>、<strong>tuple</strong>、<strong>函数</strong>、<strong>void</strong>、<strong>never</strong>、<strong>any</strong>、<strong>unknown</strong>、<strong>Number、String、Boolean、Symbol</strong>、<strong>Object</strong></p>
<h4 id="enum"><a href="#enum" class="headerlink" title="enum"></a>enum</h4><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-comment">// enum 枚举</span><br><span class="hljs-keyword">enum</span> <span class="hljs-title class_">Gender</span> &#123;<br>    <span class="hljs-title class_">Male</span> = <span class="hljs-number">0</span>,<br>    <span class="hljs-title class_">Female</span> = <span class="hljs-number">1</span><br>&#125;<br><br><span class="hljs-keyword">let</span> <span class="hljs-attr">i</span>:&#123;<span class="hljs-attr">name</span>:<span class="hljs-built_in">string</span>,<span class="hljs-attr">gender</span>:<span class="hljs-title class_">Gender</span>&#125;<br><br>i = &#123;<br>    <span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;孙悟空&#x27;</span>,<br>    <span class="hljs-attr">gender</span>: <span class="hljs-title class_">Gender</span>.<span class="hljs-property">Male</span><br>&#125;<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(i.<span class="hljs-property">gender</span> === <span class="hljs-title class_">Gender</span>.<span class="hljs-property">Male</span>)<br></code></pre></td></tr></table></figure>

<h4 id="Array"><a href="#Array" class="headerlink" title="Array"></a>Array</h4><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">list</span>: <span class="hljs-built_in">number</span>[] = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];<br><span class="hljs-keyword">let</span> <span class="hljs-attr">list</span>: <span class="hljs-title class_">Array</span>&lt;<span class="hljs-built_in">number</span>&gt; = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];<br></code></pre></td></tr></table></figure>

<h4 id="Tuple（元祖）"><a href="#Tuple（元祖）" class="headerlink" title="Tuple（元祖）"></a>Tuple（元祖）</h4><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">x</span>: [<span class="hljs-built_in">string</span>, <span class="hljs-built_in">number</span>];<br>x = [<span class="hljs-string">&quot;hello&quot;</span>, <span class="hljs-number">10</span>]; <br></code></pre></td></tr></table></figure>

<h4 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h4><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs ts"><br></code></pre></td></tr></table></figure>

<h4 id="void（空值）"><a href="#void（空值）" class="headerlink" title="void（空值）"></a>void（空值）</h4><p>JavaScript 没有空值（Void）的概念，在 TypeScript 中，可以用 <code>void</code> 表示没有任何返回值的函数：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">function</span> <span class="hljs-title function_">alertName</span>(<span class="hljs-params"></span>): <span class="hljs-built_in">void</span> &#123;<br>    <span class="hljs-title function_">alert</span>(<span class="hljs-string">&#x27;My name is Tom&#x27;</span>);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>声明一个 <code>void</code> 类型的变量没有什么用，因为你只能将它赋值为 <code>undefined</code> 和 <code>null</code></p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">unusable</span>: <span class="hljs-built_in">void</span> = <span class="hljs-literal">undefined</span>;<br></code></pre></td></tr></table></figure>

<p>与 <code>void</code> 的区别是，<code>undefined</code> 和 <code>null</code> 是所有类型的子类型。也就是说 <code>undefined</code> 类型的变量，可以赋值给 <code>number</code> 类型的变量：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-comment">// 这样不会报错</span><br><span class="hljs-keyword">let</span> <span class="hljs-attr">num</span>: <span class="hljs-built_in">number</span> = <span class="hljs-literal">undefined</span>;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">num</span>: <span class="hljs-built_in">number</span> = u;<br></code></pre></td></tr></table></figure>

<p>而 <code>void</code> 类型的变量不能赋值给 <code>number</code> 类型的变量</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">u</span>: <span class="hljs-built_in">void</span>;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">num</span>: <span class="hljs-built_in">number</span> = u;<br><span class="hljs-comment">// Type &#x27;void&#x27; is not assignable to type &#x27;number&#x27;.</span><br></code></pre></td></tr></table></figure>

<h4 id="never"><a href="#never" class="headerlink" title="never"></a>never</h4><p>表示那些永不存在的值的类型，值会永不存在的两种情况：</p>
<ol>
<li><p>如果一个函数执行时抛出了<strong>异常</strong>，那么这个函数永远不存在返回值（因为抛出异常会直接中断程序运行，这使得程序运行不到返回值那一步，即具有不可达的终点，也就永不存在返回了）；</p>
</li>
<li><p>函数中执行无限循环的代码（<strong>死循环</strong>），使得程序永远无法运行到函数返回值那一步，永不存在返回。</p>
</li>
</ol>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-comment">// 异常</span><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">err</span>(<span class="hljs-params">msg: <span class="hljs-built_in">string</span></span>): <span class="hljs-built_in">never</span> &#123; <span class="hljs-comment">// OK</span><br>  <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Error</span>(msg); <br>&#125;<br><br><span class="hljs-comment">// 死循环</span><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">loopForever</span>(<span class="hljs-params"></span>): <span class="hljs-built_in">never</span> &#123; <span class="hljs-comment">// OK</span><br>  <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) &#123;&#125;;<br>&#125;<br></code></pre></td></tr></table></figure>

<h4 id="any"><a href="#any" class="headerlink" title="any"></a>any</h4><p>在 TypeScript 中，任何类型都可以被归为 any 类型。这让 any 类型成为了类型系统的顶级类型.</p>
<p>如果是一个普通类型，在赋值过程中改变类型是不被允许的：</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">a</span>: <span class="hljs-built_in">string</span> = <span class="hljs-string">&#x27;seven&#x27;</span>;<br>a = <span class="hljs-number">7</span>;<br><span class="hljs-comment">// TS2322: Type &#x27;number&#x27; is not assignable to type &#x27;string&#x27;.</span><br></code></pre></td></tr></table></figure>

<p>但如果是 <code>any</code> 类型，则允许被赋值为任意类型。在any上访问任何属性都是允许的,也允许调用任何方法.</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">a</span>: <span class="hljs-built_in">any</span> = <span class="hljs-number">666</span>;<br>a = <span class="hljs-string">&quot;Semlinker&quot;</span>;<br>a = <span class="hljs-literal">false</span>;<br>a = <span class="hljs-number">66</span><br>a = <span class="hljs-literal">undefined</span><br>a = <span class="hljs-literal">null</span><br>a = []<br>a = &#123;&#125;<br></code></pre></td></tr></table></figure>

<p>变量如果在声明的时候，未指定其类型，那么它会被识别为任意值类型。如果我们使用 <code>any</code> 类型，就无法使用 TypeScript 提供的大量的保护机制。请记住，<code>any 是魔鬼！</code>尽量不要用any。为了解决 <code>any</code> 带来的问题，TypeScript 3.0 引入了 <code>unknown</code> 类型。</p>
<h4 id="unknow"><a href="#unknow" class="headerlink" title="unknow"></a>unknow</h4><p><code>unknown</code>与<code>any</code>一样，所有类型都可以分配给<code>unknown</code>。</p>
<blockquote>
<p>unknown与any的最大区别是：</p>
<p> 任何类型的值可以赋值给any，同时any类型的值也可以赋值给任何类型。unknown任何类型的值都可以赋值给它，但它只能赋值给unknown和any</p>
</blockquote>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">notSure</span>: <span class="hljs-built_in">any</span> = <span class="hljs-number">4</span>;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">uncertain</span>: <span class="hljs-built_in">number</span> = notSure; <span class="hljs-comment">// ok</span><br><br><span class="hljs-keyword">let</span> <span class="hljs-attr">notSure</span>: <span class="hljs-built_in">unknown</span> = <span class="hljs-number">4</span>;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">uncertain</span>: <span class="hljs-built_in">number</span> = notSure; <span class="hljs-comment">// Error</span><br></code></pre></td></tr></table></figure>

<h4 id="Number、String、Boolean、Symbol"><a href="#Number、String、Boolean、Symbol" class="headerlink" title="Number、String、Boolean、Symbol"></a>Number、String、Boolean、Symbol</h4><p>这几种是相应原始类型的包装对象，姑且称之为对象类型。从类型兼容性上看，原始类型兼容对应的对象类型，反过来对象类型不兼容对应的原始类型。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">num</span>: <span class="hljs-built_in">number</span>;<br><span class="hljs-keyword">let</span> <span class="hljs-title class_">Num</span>: <span class="hljs-title class_">Number</span>;<br><span class="hljs-title class_">Num</span> = num; <span class="hljs-comment">// ok</span><br>num = <span class="hljs-title class_">Num</span>; <span class="hljs-comment">// ts(2322)报错</span><br></code></pre></td></tr></table></figure>

<p><strong>不要使用对象类型来注解值的类型，因为这没有任何意义。</strong></p>
<h4 id="object、Object-和"><a href="#object、Object-和" class="headerlink" title="object、Object 和 {}"></a>object、Object 和 {}</h4><p>小 object 代表的是所有非原始类型，也就是说我们不能把原始类型赋值给 object。在严格模式下，<code>null</code> 和 <code>undefined</code> 类型也不能赋给 object。</p>
<p>大Object 代表所有拥有 toString、hasOwnProperty 方法的类型，所以所有原始类型、非原始类型都可以赋给 Object。同样，在严格模式下，null 和 undefined 类型也不能赋给 Object。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">lowerCaseObject</span>: <span class="hljs-built_in">object</span>;<br>lowerCaseObject = <span class="hljs-number">1</span>; <span class="hljs-comment">// ts(2322)</span><br>lowerCaseObject = <span class="hljs-string">&#x27;a&#x27;</span>; <span class="hljs-comment">// ts(2322)</span><br>lowerCaseObject = <span class="hljs-literal">null</span>; <span class="hljs-comment">// ts(2322)</span><br>lowerCaseObject = <span class="hljs-literal">undefined</span>; <span class="hljs-comment">// ts(2322)</span><br>lowerCaseObject = &#123;&#125;; <span class="hljs-comment">// ok</span><br><br><span class="hljs-keyword">let</span> <span class="hljs-attr">upperCaseObject</span>: <span class="hljs-title class_">Object</span>;<br>upperCaseObject = <span class="hljs-number">1</span>; <span class="hljs-comment">// ok</span><br>upperCaseObject = <span class="hljs-string">&#x27;a&#x27;</span>; <span class="hljs-comment">// ok</span><br>upperCaseObject = <span class="hljs-literal">null</span>; <span class="hljs-comment">// ts(2322)</span><br>upperCaseObject = <span class="hljs-literal">undefined</span>; <span class="hljs-comment">// ts(2322)</span><br>upperCaseObject = &#123;&#125;; <span class="hljs-comment">// ok</span><br></code></pre></td></tr></table></figure>

<blockquote>
<p>{}、大 Object 是比小 object 更宽泛的类型（least specific），{} 和大 Object 可以互相代替，用来表示原始类型（null、undefined 除外）和非原始类型；而小 object 则表示非原始类型。</p>
</blockquote>
<p>{}用来指定对象中可以包含哪些属性，不能多也不能少，语法：{属性名：属性值,属性名：属性值}</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-comment">// 加问号表示可选属性</span><br><span class="hljs-keyword">let</span> <span class="hljs-attr">b</span>:&#123;<span class="hljs-attr">name</span>:<span class="hljs-built_in">string</span>,age?:<span class="hljs-built_in">number</span>,[<span class="hljs-attr">propName</span>: <span class="hljs-built_in">string</span>]: <span class="hljs-built_in">any</span> &#125;<br>b = &#123;<span class="hljs-attr">name</span>:<span class="hljs-string">&#x27;孙悟空&#x27;</span>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="类型断言"><a href="#类型断言" class="headerlink" title="类型断言"></a>类型断言</h3><h4 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h4><p>通过<em>类型断言</em>这种方式可以告诉编译器，“相信我，我知道自己在干什么”。类型断言有两种形式。 </p>
<p>其一是“尖括号”语法：&lt;类型&gt;</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-comment">// string[]表示字符串数组</span><br><span class="hljs-keyword">let</span> <span class="hljs-attr">e</span>:<span class="hljs-built_in">string</span>[]<br><span class="hljs-comment">// 等同于</span><br><span class="hljs-keyword">let</span> <span class="hljs-attr">g</span>:<span class="hljs-title class_">Array</span>&lt;<span class="hljs-built_in">string</span>&gt;<br></code></pre></td></tr></table></figure>

<p>另一个为<code>as</code>语法</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">someValue</span>: <span class="hljs-built_in">any</span> = <span class="hljs-string">&quot;this is a string&quot;</span>;<br><br><span class="hljs-keyword">let</span> <span class="hljs-attr">strLength</span>: <span class="hljs-built_in">number</span> = (someValue <span class="hljs-keyword">as</span> <span class="hljs-built_in">string</span>).<span class="hljs-property">length</span>;<br></code></pre></td></tr></table></figure>

<p>以上两种方式虽然没有任何区别，但是尖括号格式会与react中JSX产生语法冲突，因此我们更推荐使用 as 语法。</p>
<h4 id="非空断言"><a href="#非空断言" class="headerlink" title="非空断言"></a>非空断言</h4><p>在上下文中当类型检查器无法断定类型时，一个新的后缀表达式操作符 <code>!</code> 可以用于断言操作对象是非 null 和非 undefined 类型。</p>
<p><strong>具体而言，x! 将从 x 值域中排除 null 和 undefined 。</strong></p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">a</span>: <span class="hljs-literal">null</span> | <span class="hljs-literal">undefined</span> | <span class="hljs-built_in">string</span>;<br>a!.<span class="hljs-title function_">toString</span>(); <span class="hljs-comment">// ok</span><br>a.<span class="hljs-title function_">toString</span>(); <span class="hljs-comment">// ts(2531)</span><br></code></pre></td></tr></table></figure>

<h4 id="确定赋值断言"><a href="#确定赋值断言" class="headerlink" title="确定赋值断言"></a>确定赋值断言</h4><p>允许在实例属性和变量声明后面放置一个 <code>!</code> 号，从而告诉 TypeScript 该属性会被明确地赋值。</p>
<figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> x!: <span class="hljs-built_in">number</span>; <span class="hljs-comment">// 如果是let x: number;会报异常</span><br><span class="hljs-title function_">initialize</span>();<br><span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-number">2</span> * x); <span class="hljs-comment">// Ok</span><br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">initialize</span>(<span class="hljs-params"></span>) &#123;<br>  x = <span class="hljs-number">10</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h2 id="字面量类型"><a href="#字面量类型" class="headerlink" title="字面量类型"></a>字面量类型</h2><p>在 TypeScript 中，字面量不仅可以表示值，还可以表示类型，即所谓的字面量类型。</p>
<p>目前，TypeScript 支持 3 种字面量类型：字符串字面量类型、数字字面量类型、布尔字面量类型。</p>
<p>对应的字符串字面量、数字字面量、布尔字面量分别拥有与其值一样的字面量类型。</p>
<h3 id="字符串字面量类型"><a href="#字符串字面量类型" class="headerlink" title="字符串字面量类型"></a>字符串字面量类型</h3><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">let</span> <span class="hljs-attr">specifiedStr</span>: <span class="hljs-string">&#x27;this is string&#x27;</span> = <span class="hljs-string">&#x27;this is string&#x27;</span>;<br><span class="hljs-keyword">let</span> <span class="hljs-attr">str</span>: <span class="hljs-built_in">string</span> = <span class="hljs-string">&#x27;any string&#x27;</span>;<br>specifiedStr = str; <span class="hljs-comment">// ts(2322) 类型 &#x27;&quot;string&quot;&#x27; 不能赋值给类型 &#x27;this is string&#x27;</span><br>str = specifiedStr; <span class="hljs-comment">// ok ，但是&#x27;this is string&#x27;类型可以赋值给类型&quot;string&quot;，因为它本来就属于string的子类型</span><br></code></pre></td></tr></table></figure>

<h3 id="数字字面量类型和布尔字面量类型"><a href="#数字字面量类型和布尔字面量类型" class="headerlink" title="数字字面量类型和布尔字面量类型"></a>数字字面量类型和布尔字面量类型</h3><figure class="highlight ts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs ts"><span class="hljs-keyword">interface</span> <span class="hljs-title class_">Config</span> &#123;<br>    <span class="hljs-attr">size</span>: <span class="hljs-string">&#x27;small&#x27;</span> | <span class="hljs-string">&#x27;big&#x27;</span>;<br>    <span class="hljs-attr">isEnable</span>:  <span class="hljs-literal">true</span> | <span class="hljs-literal">false</span>;<br>    <span class="hljs-attr">margin</span>: <span class="hljs-number">0</span> | <span class="hljs-number">2</span> | <span class="hljs-number">4</span>;<br>&#125;<br></code></pre></td></tr></table></figure>

<h1 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h1><ul>
<li><a target="_blank" rel="noopener" href="https://ts.xcatliu.com/">TypeScript 入门教程</a></li>
<li><a target="_blank" rel="noopener" href="https://jkchao.github.io/typescript-book-chinese/">深入理解 TypeScript</a></li>
<li><a target="_blank" rel="noopener" href="https://www.tslang.cn/docs/home.html">TS官方文档</a></li>
</ul>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/" class="category-chain-item">前端技术栈</a>
  
  
    <span>></span>
    
  <a href="/blog/categories/%E5%89%8D%E7%AB%AF%E6%8A%80%E6%9C%AF%E6%A0%88/js/" class="category-chain-item">js</a>
  
  

  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/blog/tags/ts/">#ts</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>TypeScript(一) 简介和基本数据类型</div>
      <div>https://airfe.gitee.io/blog/2024/04/09/TypeScript(一) 简介和基本数据类型/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>Airfe</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2024年4月9日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/blog/2024/04/09/TypeScript(%E4%BA%8C)%20%E7%BC%96%E8%AF%91%E9%80%89%E9%A1%B9/" title="TypeScript(二) 编译选项">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">TypeScript(二) 编译选项</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/blog/2024/03/21/%E6%96%AD%E7%82%B9%E7%BB%AD%E5%AD%98/" title="断点续存">
                        <span class="hidden-mobile">断点续存</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appKey":"P5fzMTGSJIoTaGvmgzsUHeNZ","path":"window.location.pathname","placeholder":"发表你的看法吧~","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false,"appid":"RW68dMkEpeIOJJiBr1lPkhOS-gzGzoHsz","appkey":"P5fzMTGSJIoTaGvmgzsUHeNZ","server_url":"https://rw68dmke.lc-cn-n1-shared.com"},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
        <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> <div style="font-size: 0.85rem"> <span id="timeDate">载入天数</span> <span id="times">载入时分秒</span> <script src="js/duration.js"></script> </div> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量 
        <span id="leancloud-site-pv"></span>
         次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数 
        <span id="leancloud-site-uv"></span>
         人
      </span>
    
    

  
</div>

  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      蜀ICP备2023008943号
    </a>
  </span>
  
    
      <span>
        <a
          href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=https://beian.miit.gov.cn/"
          rel="nofollow noopener"
          class="beian-police"
          target="_blank"
        >
          
            <span style="visibility: hidden; width: 0">|</span>
            <img src="" srcset="/blog/img/loading.gif" lazyload data-original="/blog/img/police_beian.png" alt="police-icon"/>
          
          <span>京公网安备12345678号</span>
        </a>
      </span>
    
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/blog/js/events.js" ></script>
<script  src="/blog/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/blog/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/blog/js/leancloud.js" ></script>

  <script  src="/blog/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/blog/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>

        <style>
            [bg-lazy] {
                background-image: none !important;
                background-color: #eee !important;
            }
        </style>
        <script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(r){r.imageLazyLoadSetting.processImages=t;var e=r.imageLazyLoadSetting.isSPA,n=r.imageLazyLoadSetting.preloadRatio||1,c=a();function a(){var t=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")),e=Array.prototype.slice.call(document.querySelectorAll("[bg-lazy]"));return t.concat(e)}function t(){e&&(c=a());for(var t,o=0;o<c.length;o++)0<=(t=(t=c[o]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(r.innerHeight*n||document.documentElement.clientHeight*n)&&function(){var t,e,n,a,i=c[o];e=function(){c=c.filter(function(t){return i!==t}),r.imageLazyLoadSetting.onImageLoaded&&r.imageLazyLoadSetting.onImageLoaded(i)},(t=i).hasAttribute("bg-lazy")?(t.removeAttribute("bg-lazy"),e&&e()):(n=new Image,a=t.getAttribute("data-original"),n.onload=function(){t.src=a,t.removeAttribute("data-original"),e&&e()},t.src!==a&&(n.src=a))}()}function i(){clearTimeout(t.tId),t.tId=setTimeout(t,500)}t(),document.addEventListener("scroll",i),r.addEventListener("resize",i),r.addEventListener("orientationchange",i)}(this);</script></body>
</html>
